package team.seekers.oj.codetest.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import team.seekers.oj.codetest.dto.DesCreateReqDTO;
import team.seekers.oj.codetest.dto.DesManageDTO;
import team.seekers.oj.codetest.entity.vo.DesInfoVO;
import team.seekers.oj.codetest.service.CodeTestDescriptionService;
import team.seekers.oj.codetest.service.CodeTestService;
import team.seekers.oj.common.annotation.UserSession;
import team.seekers.oj.common.entity.ApiResponseBody;
import team.seekers.oj.common.entity.UserSessionDTO;
import team.seekers.oj.common.enums.ApiExceptionEnum;
import team.seekers.oj.common.util.AssertUtils;

import javax.validation.Valid;

@Slf4j
@Controller
@RequestMapping("/des/codetest")
public class CodeTestDescriptionController {

    @Autowired
    private CodeTestDescriptionService codeTestDescriptionService;

    @Autowired
    private CodeTestService codeTestService;

    @PostMapping("/create")
    @ApiResponseBody
    public Long desCreate(@RequestBody @Valid DesCreateReqDTO reqDTO,
                       @UserSession UserSessionDTO userSessionDTO) {
        // 增补
        reqDTO.setUserId(userSessionDTO.getUserId());

        return codeTestDescriptionService.desCreate(reqDTO);
    }

    @GetMapping("/remove")
    @ApiResponseBody
    public Void removeDescription(@RequestParam("codeTestId") long codeTestId,
                       @RequestParam("desId") long desId,
                       @UserSession UserSessionDTO userSessionDTO) {
        // 创建者才可修改群组
        AssertUtils.isTrue(codeTestService.isCodeTestManager(codeTestDescriptionService.getDesVO(desId).getUserId(), userSessionDTO),
                ApiExceptionEnum.USER_NOT_MATCHING, "没有权限");
        codeTestDescriptionService.removeDescription(desId);
        return null;
    }

    @PostMapping("/update")
    @ApiResponseBody
    public Void desUpdate(@RequestBody @Valid DesManageDTO reqDTO,
                       @UserSession UserSessionDTO userSessionDTO) {
        // 创建者才可修改群组
        AssertUtils.isTrue(codeTestService.isCodeTestManager(reqDTO.getUserId(), userSessionDTO),
                ApiExceptionEnum.USER_NOT_MATCHING, "没有权限");

        codeTestDescriptionService.desUpdate(reqDTO);
        return null;
    }

    @GetMapping("/info")
    @ApiResponseBody
    public DesInfoVO desInfo(@RequestParam("id") long id) {
        return codeTestDescriptionService.getDesVO(id);
    }
}
